import logging
from datetime import datetime
from peewee import fn
from api.db.db_models import RegisterInvitationCode
from api.db.services.common_service import CommonService
from api.utils import get_uuid, current_timestamp
from playhouse.shortcuts import model_to_dict


logger = logging.getLogger(__name__)

class RegisterInvitationService(CommonService):
    model = RegisterInvitationCode

    @classmethod
    def create_invite_code(cls, creator_email: str):
        """创建邀请码"""
        code = get_uuid()[:8].upper()  # 生成8位大写随机码
        try:
            return cls.model.create(
                code=code,
                creator_email=creator_email,
                is_valid=True
                # create_time/create_date 会自动填充
            )
        except Exception as e:
            logger.error(f"Create invite code error: {str(e)}")
            return None

    @classmethod
    def validate_invite_code(cls, code: str, user_email: str):
        """验证邀请码有效性"""
        try:
            invite = cls.model.get(
                (cls.model.code == code) & 
                (cls.model.is_valid == True)
            )
            
            # 更新使用信息
            invite.user_email = user_email
            invite.is_valid = False
            invite.used_time = current_timestamp()
            invite.save()  # update_time/update_date会自动更新
            
            return True
        except cls.model.DoesNotExist:
            return False
        except Exception as e:
            logger.error(f"Validate invite code error: {str(e)}")
            return False

    @classmethod
    def revoke_invite_code(cls, code_id: int):
        """作废邀请码"""
        try:
            updated = cls.model.update(
                is_valid=False,
                update_time=current_timestamp()
            ).where(cls.model.id == code_id).execute()
            return updated > 0
        except Exception as e:
            logger.error(f"Revoke invite code error: {str(e)}")
            return False

    @classmethod
    def get_invite_codes(cls, page: int = 1, per_page: int = 10):
        """分页获取邀请码列表"""
        query = cls.model.select().order_by(cls.model.create_time.desc())
        total = query.count()
        items = query.paginate(page, per_page)
        
        return {
            "total": total,
            "items": [model_to_dict(item) for item in items]
        }